import Reflect from "@/utils/reflect";
// import { ElMessage } from "element-plus";
import { AnyFunc } from "./type";
import MessageError from "@/errors/MessageError";

export function Validate(phase?: string) {
  return function(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor<AnyFunc>) {
    Reflect.pushValue(target, ["validate", phase || ""], propertyKey);
  }
}

export function ValidateIntercept(...phases: string[]) {
  phases = phases.length === 0 ? [""] : phases;
  return function(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor<AnyFunc>) {
    Reflect.setValue(target, ["ValidateIntercept", propertyKey], descriptor.value);
    descriptor.value = async function(...args) {
      var instance: any = this;
      try {
        try {
          for (const phase of phases) {
            var loadPropertys: string[] = Reflect.getValue(target, ["validate", phase], []);
            for (const loadProperty of loadPropertys) {
              const validateFunc = instance[loadProperty];
              if (typeof validateFunc === "function") {
                await validateFunc();
              }
            }
          }
        } catch (error) {
          if (error instanceof Error) {
            throw new MessageError(error.message);
          }
        }
        await Reflect.getValue<AnyFunc>(target, ["ValidateIntercept", propertyKey]).call(this, ...args);
      } catch (error) {
        if (error instanceof MessageError) {
          // ElMessage.warning(error.message);
          alert(error.message);
        }
      }
    }
  }
}
